//
//  ZYFlyWeightManager.m
//  DesignMode
//
//  Created by wangzhipan on 2024/10/18.
//

#import "ZYFlyWeightManager.h"

static const NSUInteger kMaxCount = 1000;

@interface ZYFlyWeightManager()
@property (nonatomic, strong, nullable) NSMutableDictionary *refs;

@property (nonatomic, assign) NSUInteger objCount;
@end

@implementation ZYFlyWeightManager
- (instancetype)init
{
    if (self = [super init]) {
        self.refs = [NSMutableDictionary dictionary];
        self.objCount = 0;
    }
    return self;
}

- (id)fetchObjForClass:(Class)class
{
    NSString *key = NSStringFromClass(class);
    NSMutableArray *pool = self.refs[key];
    if (!pool) {
        pool = [NSMutableArray array];
    }
    id obj = nil;
    if (pool.count) {
        obj = pool.lastObject;
        [pool removeLastObject];
    }
    else if (self.objCount < kMaxCount){
        obj = [[[obj class] alloc] init];
        self.objCount++;
    }
    self.refs[key] = pool;
    return obj;
}

- (void)storeObjOnReusePool:(id)obj
{
    if (!obj) {
        return;
    }
    NSString *key = NSStringFromClass([obj class]);
    NSMutableArray *pool = self.refs[key];
    if (!pool) {
        pool = [NSMutableArray array];
    }
    [pool addObject:obj];
    self.refs[key] = pool;
}
@end
